import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Typography, Card, Avatar, Upload, App, Divider, Checkbox, Row, Col } from 'antd';
import { UserOutlined, UploadOutlined, EditOutlined, LockOutlined, SafetyCertificateOutlined, CheckCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd/es/upload/interface';
import axios from 'axios';
import { getFullMediaUrl } from '../utils/config';

const { Title } = Typography;

const AccountSettings: React.FC = () => {
    const { message } = App.useApp();
    const [form] = Form.useForm();
    const [passwordForm] = Form.useForm();
    const [currentUser, setCurrentUser] = useState<any>(null);
    const [avatarUrl, setAvatarUrl] = useState<string>('');
    const [uploading, setUploading] = useState(false);
    const [previewUrl, setPreviewUrl] = useState<string>('');
    const [updating, setUpdating] = useState(false);
    const [passwordLoading, setPasswordLoading] = useState(false);
    const [changePassword, setChangePassword] = useState(false);
    const [newPassword, setNewPassword] = useState('');

    // 密码强度检查
    const getPasswordStrength = (password: string) => {
        if (!password) return { level: 0, text: '', color: '' };
        let score = 0;
        if (password.length >= 8) score++;
        if (/[a-z]/.test(password)) score++;
        if (/[A-Z]/.test(password)) score++;
        if (/[0-9]/.test(password)) score++;
        if (/[^A-Za-z0-9]/.test(password)) score++;
        if (score < 2) return { level: 1, text: '弱', color: '#ff4d4f' };
        if (score < 4) return { level: 2, text: '中等', color: '#faad14' };
        return { level: 3, text: '强', color: '#52c41a' };
    };

    const passwordStrength = getPasswordStrength(newPassword);

    // Load user profile data including avatar
    useEffect(() => {
        const loadUserProfile = async () => {
            const token = localStorage.getItem('authToken');
            if (!token) return;

            try {
                const response = await axios.get('/api/auth/user/', {
                    headers: { 'Authorization': `Token ${token}` }
                });
                setCurrentUser(response.data);

                if (response.data.profile?.avatar) {
                    setAvatarUrl(getFullMediaUrl(response.data.profile.avatar) || '');
                }
            } catch (error) {
                console.error('Failed to load user profile:', error);
            }
        };

        loadUserProfile();
    }, []);

    // Handle form submission for username update
    const onFinish = async (values: any) => {
        const token = localStorage.getItem('authToken');
        if (!token) {
            message.error('请先登录');
            return;
        }

        setUpdating(true);
        try {
            const response = await axios.patch('/api/auth/update-username/', {
                username: values.username
            }, {
                headers: { 'Authorization': `Token ${token}` }
            });
            message.success('用户名更新成功！');
            setCurrentUser(response.data);
            localStorage.setItem('username', values.username);
            window.dispatchEvent(new CustomEvent('userProfileUpdated', {
                detail: { displayName: values.username }
            }));
        } catch (error: any) {
            const errorMessage = error.response?.data?.error ||
                                error.response?.data?.username?.[0] ||
                                '更新失败，请重试';
            message.error(errorMessage);
        } finally {
            setUpdating(false);
        }
    };

    // Handle password change form submission
    const onPasswordFinish = async (values: any) => {
        const token = localStorage.getItem('authToken');
        if (!token) {
            message.error('请先登录');
            return;
        }

        setPasswordLoading(true);
        try {
            await axios.post('/api/auth/change-password/', {
                current_password: values.currentPassword,
                new_password: values.newPassword
            }, {
                headers: { 'Authorization': `Token ${token}` }
            });
            message.success('密码修改成功！');
            passwordForm.resetFields();
            setChangePassword(false);
            setNewPassword('');
        } catch (error: any) {
            const errorMessage = error.response?.data?.error ||
                                error.response?.data?.current_password?.[0] ||
                                error.response?.data?.new_password?.[0] ||
                                '密码修改失败，请重试';
            message.error(errorMessage);
        } finally {
            setPasswordLoading(false);
        }
    };

    // Handle avatar upload
    const handleAvatarUpload = async (file: File) => {
        const token = localStorage.getItem('authToken');
        if (!token) {
            message.error('请先登录');
            return false;
        }

        setUploading(true);
        const formData = new FormData();
        formData.append('avatar', file);

        try {
            const response = await axios.patch('/api/auth/profile/', formData, {
                headers: {
                    'Authorization': `Token ${token}`,
                    'Content-Type': 'multipart/form-data',
                }
            });

            if (response.data.profile?.avatar) {
                const fullAvatarUrl = getFullMediaUrl(response.data.profile.avatar) || '';
                setAvatarUrl(fullAvatarUrl);
                setPreviewUrl('');
                message.success('头像更新成功！');
                window.dispatchEvent(new CustomEvent('userProfileUpdated', {
                    detail: { avatarUrl: fullAvatarUrl }
                }));
            }
        } catch (error: any) {
            const errorMessage = error.response?.data?.error ||
                                error.response?.data?.avatar?.[0] ||
                                '头像上传失败，请重试';
            message.error(errorMessage);
        } finally {
            setUploading(false);
        }
        return false;
    };

    const uploadProps: UploadProps = {
        name: 'avatar',
        showUploadList: false,
        beforeUpload: (file) => {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                message.error('只能上传 JPG/PNG 格式的图片!');
                return false;
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                message.error('图片大小必须小于 2MB!');
                return false;
            }
            const reader = new FileReader();
            reader.onload = (e) => setPreviewUrl(e.target?.result as string);
            reader.readAsDataURL(file);
            handleAvatarUpload(file);
            return false;
        },
    };

    return (
        <div>
            <Title level={3}>
                <EditOutlined style={{ marginRight: 8 }} />
                个人设置
            </Title>
            <Card>
                <Divider orientation="left">头像管理</Divider>
                <div style={{ display: 'flex', alignItems: 'center', marginBottom: 24 }}>
                    <Avatar
                        size={64}
                        src={previewUrl || avatarUrl || null}
                        icon={!previewUrl && !avatarUrl ? <UserOutlined /> : undefined}
                    />
                    <Upload {...uploadProps}>
                        <Button
                            icon={<UploadOutlined />}
                            style={{ marginLeft: 16 }}
                            loading={uploading}
                        >
                            {uploading ? '上传中...' : '修改头像'}
                        </Button>
                    </Upload>
                </div>

                <Divider orientation="left">基本信息</Divider>
                <Form
                    form={form}
                    key={currentUser?.username}
                    name="account"
                    layout="vertical"
                    initialValues={{ username: currentUser?.username || '' }}
                    onFinish={onFinish}
                >
                    <Form.Item
                        label="用户名"
                        name="username"
                        rules={[
                            { required: true, message: '请输入用户名!' },
                            { min: 3, message: '用户名至少3个字符!' },
                            { max: 20, message: '用户名最多20个字符!' }
                        ]}
                    >
                        <Input prefix={<UserOutlined />} placeholder="输入用户名" />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" loading={updating}>
                            {updating ? '保存中...' : '保存更改'}
                        </Button>
                    </Form.Item>
                </Form>

                <Divider orientation="left">
                    <SafetyCertificateOutlined style={{ marginRight: 8 }} />
                    密码管理
                </Divider>
                <div style={{ marginBottom: 16 }}>
                    <Checkbox
                        checked={changePassword}
                        onChange={(e) => {
                            setChangePassword(e.target.checked);
                            if (!e.target.checked) {
                                passwordForm.resetFields();
                                setNewPassword('');
                            }
                        }}
                    >
                        修改密码
                    </Checkbox>
                </div>

                {changePassword && (
                    <Form
                        form={passwordForm}
                        name="security"
                        layout="vertical"
                        onFinish={onPasswordFinish}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="当前密码"
                            name="currentPassword"
                            rules={[{ required: true, message: '请输入你当前的密码!' }]}
                        >
                            <Input.Password prefix={<LockOutlined />} placeholder="输入当前密码" autoComplete="current-password" />
                        </Form.Item>
                        <Row gutter={16}>
                            <Col span={12}>
                                <Form.Item
                                    label="新密码"
                                    name="newPassword"
                                    rules={[
                                        { required: true, message: '请输入新密码!' },
                                        { min: 6, message: '密码至少6个字符!' }
                                    ]}
                                >
                                    <Input.Password
                                        prefix={<LockOutlined />}
                                        placeholder="输入新密码"
                                        onChange={(e) => setNewPassword(e.target.value)}
                                        autoComplete="new-password"
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="确认新密码"
                                    name="confirmPassword"
                                    dependencies={['newPassword']}
                                    rules={[
                                        { required: true, message: '请确认新密码!' },
                                        ({ getFieldValue }) => ({
                                            validator(_, value) {
                                                if (!value || getFieldValue('newPassword') === value) {
                                                    return Promise.resolve();
                                                }
                                                return Promise.reject(new Error('两次输入的密码不一致!'));
                                            },
                                        }),
                                    ]}
                                >
                                    <Input.Password
                                        prefix={<LockOutlined />}
                                        placeholder="再次输入新密码"
                                        autoComplete="new-password"
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                        
                        {newPassword && (
                            <div style={{ marginBottom: 16 }}>
                                <Typography.Text strong>密码强度: </Typography.Text>
                                <span style={{ color: passwordStrength.color }}>
                                    {passwordStrength.level === 1 && <ExclamationCircleOutlined />}
                                    {passwordStrength.level === 2 && <ExclamationCircleOutlined />}
                                    {passwordStrength.level === 3 && <CheckCircleOutlined />}
                                    {' ' + passwordStrength.text}
                                </span>
                                <div style={{ marginTop: 8 }}>
                                    <Typography.Text type="secondary" style={{ fontSize: '12px' }}>
                                        建议密码包含：大写字母、小写字母、数字、特殊字符，长度至少8位
                                    </Typography.Text>
                                </div>
                            </div>
                        )}

                        <Form.Item>
                            <Button type="primary" htmlType="submit" loading={passwordLoading} danger>
                                {passwordLoading ? '修改中...' : '确认修改密码'}
                            </Button>
                        </Form.Item>
                    </Form>
                )}
            </Card>
        </div>
    );
};

export default AccountSettings;